<template>
  <t-form ref="form" :class="['item-container', `login-${type}`]" :data="formData" :rules="FORM_RULES" :key="type"
    label-width="0" @submit="onSubmit">
    <template v-if="type === 'password'">
      <t-form-item name="username">
        <t-input v-model="formData.username" size="large" placeholder="请输入账号">
          <template #prefix-icon>
            <user-icon />
          </template>
        </t-input>
      </t-form-item>


      <t-form-item name="password">
        <t-input v-model="formData.password" size="large" :type="showPsw ? 'text' : 'password'" clearable key="password"
          placeholder="请输入登录密码">
          <template #prefix-icon>
            <lock-on-icon />
          </template>
          <template #suffix-icon>
            <browse-icon v-if="showPsw" @click="showPsw = !showPsw" key="browse" />
            <browse-off-icon v-else @click="showPsw = !showPsw" key="browse-off" />
          </template>
        </t-input>
      </t-form-item>
      <t-form-item class="verification-code" name="imageCode">
        <t-input v-model="formData.imageCode" size="large" placeholder="请输入图形验证码">
          <template #prefix-icon>
            <t-icon name="lock-on"></t-icon>
          </template>
        </t-input>
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </t-form-item>

      <div class="check-container remember-pwd">
        <span class="tip"></span>
        <!--              <t-checkbox>记住账号</t-checkbox>-->
        <span class="tip" @click="switchType('resetPassword')">忘记密码？</span>
      </div>
    </template>

    <!-- 扫码登录 -->
    <template v-else-if="type === 'qrcode'">
      <!--          <div class="tip-container">-->
      <!--            <span class="tip">请使用微信扫一扫登录</span>-->
      <!--            <span class="refresh"-->
      <!--              >刷新-->
      <!--              <refresh-icon color="#0052D9" />-->
      <!--            </span>-->
      <!--          </div>-->
      <wechat-login :appid="appid" :redirect_uri="redirect_uri">
      </wechat-login>
      <!--          <qrcode-vue style="display:flex;justify-content: center" value="" :size="192" level="H" />-->
    </template>

    <!-- 手机号登录 -->
    <template v-else-if="type === 'phone'">
      <t-form-item name="phoneNumber">
        <t-input v-model="formData.phoneNumber" size="large" placeholder="请输入您的手机号">
          <template #prefix-icon>
            <user-icon />
          </template>
        </t-input>
      </t-form-item>
      <t-form-item class="verification-code" name="imageCode">
        <t-input v-model="formData.imageCode" size="large" placeholder="请输入图形验证码">
          <template #prefix-icon>
            <t-icon name="lock-on"></t-icon>
          </template>
        </t-input>
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </t-form-item>
      <t-form-item class="verification-code" name="code">
        <t-input v-model="formData.code" size="large" placeholder="请输入短信验证码" key="verifyCode">
          <template #prefix-icon>
            <t-icon name="lock-on"></t-icon>
          </template>
        </t-input>
        <t-button variant="outline" :disabled="countDown > 0" @click="handleCounter(1)">
          {{ countDown === 0 ? '发送验证码' : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
      <div class="warn-container">
        <span class="tip"></span>
        <t-tag class="warn-tip" variant="light">{{ site_tag === 'jtt' ? '归属地为江西省外手机号暂时接收不到验证码' :
          '未加白名单移动用户手机号暂时接收不到验证码' }}</t-tag>
      </div>
    </template>

    <!-- 手机号密码重置 -->
    <template v-else>
      <t-form-item name="phoneNumber">
        <t-input v-model="formData.phoneNumber" size="large" placeholder="请输入您的手机号">
          <template #prefix-icon>
            <user-icon />
          </template>
        </t-input>
      </t-form-item>
      <t-form-item class="verification-code" name="imageCode">
        <t-input v-model="formData.imageCode" size="large" placeholder="请输入图形验证码">
          <template #prefix-icon>
            <t-icon name="lock-on"></t-icon>
          </template>
        </t-input>
        <img :src="codeUrl" @click="getCode" class="login-code-img" />
      </t-form-item>
      <t-form-item class="verification-code" name="code">
        <t-input v-model="formData.code" size="large" placeholder="请输入短信验证码" key="verifyCode">
          <template #prefix-icon>
            <t-icon name="lock-on"></t-icon>
          </template>
        </t-input>
        <t-button variant="outline" :disabled="countDown > 0" @click="handleCounter(2)">
          {{ countDown === 0 ? '发送验证码' : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
      <t-form-item name="newPassword" help="请输入 8-20 个字符，需同时包含数字、字母以及特殊符号">
        <t-input v-model="formData.newPassword" size="large" :type="showPsw ? 'text' : 'password'" clearable
          key="password" autocomplete="new-password" placeholder="请输入登录密码">
          <template #prefix-icon>
            <lock-on-icon />
          </template>
          <template #suffix-icon>
            <browse-icon v-if="showPsw" @click="showPsw = !showPsw" key="browse" />
            <browse-off-icon v-else @click="showPsw = !showPsw" key="browse-off" />
          </template>
        </t-input>
      </t-form-item>
    </template>

    <t-form-item style="margin-bottom: 25px" v-if="!['qrcode', 'resetPassword'].includes(type)" class="btn-container">
      <t-button block size="large" type="submit" :loading="loginLoading">{{ loginLoading ? '登录中...' : '登录' }}</t-button>
    </t-form-item>

    <t-form-item style="margin-bottom: 25px" v-if="type === 'resetPassword'" class="btn-container">
      <t-button block size="large" @click="resetPassWord" :loading="loginLoading">{{ loginLoading ? '重置密码中...' : '重置密码'
        }}</t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">使用账号密码登录</span>
      <!--      <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')">使用微信扫码登录</span>-->
      <span v-if="type !== 'phone' && site_tag === 'jtt'" class="tip" @click="switchType('phone')">使用手机号登录</span>
    </div>
  </t-form>
</template>
<script>
// import { encrypt } from "@/utils/jsencrypt";
import { encrypt } from "@/utils/encrypt";
// import md5 from "js-md5"
import WechatLogin from "../../../components/WechatLogin/index.vue";
import { UserIcon, LockOnIcon, BrowseOffIcon, BrowseIcon, RefreshIcon } from 'tdesign-icons-vue';
import { sendCodeWidthImageCode, sendCodeWidthImageCode2, getCodeImg2, resetPassWordByPhone } from '@/api/login'


const INITIAL_DATA = {
  phoneNumber: '',
  username: '',
  password: '',
  hash_password: '',
  msg_code: '',
  code: '',
  checked: false,
  uuid: '',
  imageCode: '',
  newPassword: '',
};

const FORM_RULES = {
  phoneNumber: [{ required: true, message: '手机号必填', type: 'error' }, {
    pattern: /^\d{11}$/,
    message: '手机号错误',
    type: 'error',
  },],
  username: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  code: [{ required: true, message: '验证码必填', type: 'error' }, {
    pattern: /^\d{1,11}$/,
    message: '验证码错误',
    type: 'error',
  }],
  imageCode: [{ required: true, message: '图形验证码必填', type: 'error' }],
  newPassword: [
    {
      required: true,
      message: "新密码不能为空",
    },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9~!@#$%^&*]{8,20}/,
      message: '请输入 8-20 个字符，需同时包含数字、字母以及特殊符号',
      type: 'error',
      trigger: 'blur'
    },
  ],

};

/** 高级详情 */
export default {
  name: 'Login',
  components: {
    UserIcon,
    LockOnIcon,
    BrowseOffIcon,
    BrowseIcon,
    // RefreshIcon,
    WechatLogin,
  },
  props: {
    loginType: {
      type: String,
      default: "password"
    },
  },
  data() {
    return {
      appid: 'wxbdc5610cc59c1631',
      redirect_uri: 'https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do',
      site_tag: import.meta.env.VITE_SITE_TAG,
      loginLoading: false,
      FORM_RULES,
      type: this.loginType,
      formData: { ...INITIAL_DATA },
      showPsw: false,
      countDown: 0,
      intervalTimer: null,
      // 验证码开关
      captchaOnOff: true,
      codeUrl: '',
    };
  },
  created() {
    const code = this.$route.query && this.$route.query.code;
    if (code) {
      // 微信登陆
    }
    this.getCode();
  },
  beforeDestroy() {
    clearInterval(this.intervalTimer);
  },
  methods: {
    getCode() {
      getCodeImg2().then((res) => {
        this.codeUrl = `data:image/gif;base64,${res.data.imageBase64}`;
        this.formData.uuid = res.data.uuid;
      }).catch(err => {
        this.$message.error(err.toString());
      });
    },
    switchType(val) {
      this.$refs.form.clearValidate();
      this.type = val;
      this.$refs.form.reset();
      if (['resetPassword', 'phone', 'password'].includes(val)) {
        this.getCode();
      }
    },
    resetPassWord() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loginLoading = true;
          resetPassWordByPhone(
            {
              ...this.formData,
              password: encrypt(this.formData.newPassword),
              newPassword: '',
            }
          ).then((res) => {
            this.$message.success('重置密码成功');
            this.type = 'password';
            this.loginLoading = false;
          }).catch(err => {
            this.loginLoading = false;
            this.$message.error(err.toString());
            this.getCode()
          });
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
    async onSubmit({ validateResult }) {
      if (validateResult === true) {
        this.loginLoading = true;
        this.$store
          .dispatch("user/Login", {
            ...this.formData,
            password: encrypt(this.formData.password),
            loginType: this.type,
            // code: this.formData.imageCode,
          })
          .then(() => {
            this.$store.dispatch('user/GetInfo').then(() => {
              this.$store.dispatch('permission/initRoutes', {
                permissions: this.$store.state.user.permissions, services: this.$store.state.user.services
              }).then(() => {
                this.loginLoading = false;
                if (this.$store.state.permission.routers.length <= 0) {
                  this.$message.error('当前用户未分配权限');
                } else {
                  this.$message.success('登录成功');
                  // 设置当前子系统的路由
                  this.$store.commit('permission/setCurrentSystemRouters', this.$store.state.permission.routers[0]);
                  if (this.$store.state.user.roles.includes("ROLE_DEFAULT")) { // 针对未分配角色避免空白跳用户中心
                    this.$router.push("/user/index");
                  } else if (this.$store.state.user.roles.includes("zjk")) {
                    this.$router.push("/zjk");
                  } else {
                    this.$router.push(this.$route.query.redirect || this.$store.state.permission.routers[0].path);
                  }
                }
              });
            }).catch(err => {
              this.loginLoading = false;
              this.$message.error(err.toString());
              this.getCode();
            })

          })
          .catch((e) => {
            this.loginLoading = false;
            this.$message.error(e.toString());
            this.getCode();
          });
      }
    },
    handleCounter(type) {
      this.$refs.form.validate({
        fields: ['phoneNumber', 'imageCode']
      }).then((validateResult) => {
        if (validateResult === true) {
          if (type === 1) {
            sendCodeWidthImageCode({
              phoneNumber: this.formData.phoneNumber,
              code: this.formData.imageCode,
              uuid: this.formData.uuid,
            }).then(() => {
              this.countDown = 60;
              this.intervalTimer = setInterval(() => {
                if (this.countDown > 0) {
                  this.countDown -= 1;
                } else {
                  clearInterval(this.intervalTimer);
                  this.countDown = 0;
                }
              }, 1000);
            })
              .catch((e) => {
                this.$message.error(e.toString());
                this.getCode();
              })
          } else {
            sendCodeWidthImageCode2({
              phoneNumber: this.formData.phoneNumber,
              code: this.formData.imageCode,
              uuid: this.formData.uuid,
            }).then(() => {
              this.countDown = 60;
              this.intervalTimer = setInterval(() => {
                if (this.countDown > 0) {
                  this.countDown -= 1;
                } else {
                  clearInterval(this.intervalTimer);
                  this.countDown = 0;
                }
              }, 1000);
            })
              .catch((e) => {
                this.$message.error(e.toString());
                this.getCode();
              })
          }

        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  },
};
</script>
